def top_sort(D):
    n = len(D)
    ind, outd, V = [0] * n, [0] * n, [0] * n

    for x in range(len(D)):
        for y in range(len(D[x])):
            if D[x][y] == 1:
                ind[y] += 1
                outd[x] += 1

    import collections

    Q = collections.deque()
    for x in range(n):
        if ind[x] == 0 and V[x] == 0:
            Q.append(x)
            V[x] = 1
    while Q:
        h = Q[0]
        for y in range(len(D)):
            if D[h][y] == 1:
                ind[y] -= 1
        print(Q.popleft())
        for x in range(n):
            if ind[x] == 0 and V[x] == 0:
                Q.append(x)
                V[x] = 1


D = [[0, 1, 0, 0],
     [0, 0, 1, 0],
     [0, 0, 0, 0],
     [0, 0, 1, 0]]

top_sort(D)
